//
//  CNHomeViewController.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/19.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit
import SVPullToRefresh
import SVProgressHUD

private let reuseIdentifier = "CNStatusCell"

class CNHomeViewController: CNBaseTableViewController {
    
    var statuses: [CNStatus]? {
        // 获取到新数据后,刷新界面
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if CNUserAccountViewModel.sharedInstance.isLogin {
            
            setupNavigationBar()
            setupTitleButton()
            prepareTableView()
            // 暴力测试:直接加载网络数据
//            CNStatusViewModel.sharedInstance.loadStatuses { (statuses, error) -> () in
//                if error != nil {
//                    CNPrint(item: "加载微博数据出错")
//                } else {
//                    self.statuses = statuses
//                }
//            }
        }
    }
    
    private func prepareTableView() {
        
        tableView.registerClass(CNStatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        // 根据子控件的布局自动确定高度
//        tableView.estimatedRowHeight = 100 // 缓存行高,不要预估行高
        tableView.rowHeight = UITableViewAutomaticDimension
        // 去掉cell的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        // 添加下拉刷新界面
//        tableView.addSubview(pullDownRefreshView)
//        pullDownRefreshView.pullToRefreshHandler = { () -> () in
//            CNPrint(item: "开始刷新")
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//                CNPrint(item: "刷新完成")
//                self.pullDownRefreshView.endRefreshing()
//            })
//        }
        // 下拉刷新
        tableView.addPullToRefreshHandler { [weak self] () -> () in
            
            self?.loadNewStatuses()
        }
        tableView.scrollViewStartRefreshing()
//        // 上拉加载更多
//        tableView.addInfiniteScrollingWithActionHandler { [weak self] () -> () in
//            
//            self?.loadOldStatuses()
//        }
    }

    private func loadNewStatuses() {
       
        let since_id = statuses?.first?.id ?? 0
        
        CNStatusViewModel.sharedInstance.loadStatuses(since_id, max_id: 0) { [weak self] (statuses, error) -> () in
            // 不管成功与否都要结束刷新
            self?.tableView.scrollViewEndRefreshing()
            
            if error != nil {
                CNPrint(item: "loadNewStatuses: 刷新微博数据出错")
                return
            } else {
                let count = statuses?.count ?? 0
                if since_id > 0 {
                    self?.showTipView(count)
                }
                if count == 0 { // 没有加载到新微薄
                    CNPrint(item: "loadNewStatuses: 没有新的微博数据")
                    return
                }
                if since_id > 0 { // 下拉刷新,拼接新旧微博数据
                    self?.statuses = statuses! + self!.statuses!
//                    CNPrint(item: "加载了新微薄")
                } else { // 第一次进入主界面自动加载微博
                    self?.statuses = statuses
//                    CNPrint(item: "\(statuses?.first?.created_at)")
                    // 第一次微博数据加载完成后再添加'上拉加载'功能
                    // (防止第一次进入主界面时,两个数据请求同时进行)
                    // 上拉加载更多
                    self?.tableView.addInfiniteScrollingWithActionHandler { () -> () in
                        
                        self?.loadOldStatuses()
                    }
                }
            }
        }
    }
    
    private func loadOldStatuses() {
        
        let max_id = self.statuses?.last?.id ?? 0
        
        CNStatusViewModel.sharedInstance.loadStatuses(0, max_id: max_id) { [weak self] (statuses, error) -> () in
            // 结束加载数据
            self?.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                CNPrint(item: "loadOldStatuses: 加载更早微博数据出错")
                return
            } else {
                let count = statuses?.count ?? 0
                if count == 0 { //
                    CNPrint(item: "loadOldStatuses: 没有加载到旧的微博数据")
                    return
                }
                self?.statuses = self!.statuses! + statuses!
            }
        }
    }
    
    private func showTipView(count: Int) {
        // 解决动画叠加问题
        let animations = tipLabel.layer.animationKeys()
        if animations != nil {
            tipLabel.layer.removeAllAnimations()
        }
        tipLabel.text = count == 0 ? "暂时还没有更新的微博~" : "更新了\(count)条微博~"
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }
    
    private func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "leftItemAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightItemAction")
    }
    
    @objc private func leftItemAction() {
        SVProgressHUD.showInfoWithStatus("该功能还未实现哦")
    }
    
    @objc private func rightItemAction() {
        CNPrint(item: "rightItemAction")
    }
    
    private func setupTitleButton() {
        
        let name = CNUserAccountViewModel.sharedInstance.userAccount?.screen_name
        let button = CNHomeTitleButton(title: name, imageName: "navigationbar_arrow_down")
        button.addTarget(self, action: "titleButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = button
    }
    
    @objc private func titleButtonAction(button: CNHomeTitleButton) {
        
        button.selected = !button.selected
       
        UIView.animateWithDuration(defaultDuration, animations: { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) : CGAffineTransformIdentity
        })
        if button.selected {
            
            let popoverVC = CNPopoverViewController()
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
            popoverVC.popoverPresentationController?.delegate = self
            // 设置popover箭头指向,不设置会崩溃
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            // 设置sourceView的大小,popover会自动选择最佳位置
            popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            // 设置popover的大小
            popoverVC.preferredContentSize = CGSize(width: 200, height: 44 * popoverVC.titles.count)
            presentViewController(popoverVC, animated: true, completion: nil)
        }
    }
//    private lazy var pullDownRefreshView: CNPullDownRefreshView = CNPullDownRefreshView()
    private lazy var tipLabel: UILabel = {
        
        let label = UILabel()
        label.textColor = UIColor.whiteColor()
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(16)
        label.textAlignment = NSTextAlignment.Center
        label.frame = CGRect(x: 0, y: -64, width: UIScreen.width, height: 44)
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
    }()
 
}

// MARK: - UITableViewDelegate, UITableViewDataSource
extension CNHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // '??'表示可选没有值时,使用'??'后面的值
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! CNStatusCell
        cell.status = statuses?[indexPath.row]
        cell.delegate = self
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = self.statuses![indexPath.row]
        if status.rowHeight != nil {
//            CNPrint(item: "获取缓存行高: \(status.rowHeight)")
            return status.rowHeight!
        }
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! CNStatusCell
        cell.status = status
        // 获取cell的高度
        let rowHeight = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        // 缓存行高
        status.rowHeight = rowHeight
//        CNPrint(item: "计算行高: \(rowHeight)")
        return rowHeight
    }
    
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}

// MARK: - UIPopoverPresentationControllerDelegate
extension CNHomeViewController: UIPopoverPresentationControllerDelegate {
    // 不适配iPhone
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        let titleButton = navigationItem.titleView as! CNHomeTitleButton
        titleButtonAction(titleButton)
        return true
    }
}
// MARK: - CNStatusCellDelegate
extension CNHomeViewController: CNStatusCellDelegate {
    func cellDidClickRetweetButton(cell: CNStatusCell) {
        let retweetVC = CNRetweetViewController()
        retweetVC.id = cell.status?.id
        presentViewController(UINavigationController(rootViewController: retweetVC), animated: true, completion: nil)
    }
    func cellDidClickCommentButton(cell: CNStatusCell) {
        let commentVC = CNCommentViewController()
        commentVC.id = cell.status?.id
        presentViewController(UINavigationController(rootViewController: commentVC), animated: true, completion: nil)
    }
}
